<?php

namespace app\common\model;

use GuzzleHttp\Exception\RequestException;
use think\Db;
use think\Exception;
use think\Model;

class Commission extends Model {
    protected $autoWriteTimestamp = true;

    // 订单佣金状态变更
    public static function orderCommissionStateChange($order, $state = 50) {

        # 将未结算的直接改成已失效
        Db::name('commission')->where([
            'order_sn' => $order['order_sn'],
            'state' => ['lt', COMMISSION_STATE_SUCCESS]
        ])->update([
            'state' => $state,
            'update_time' => time(),
        ]);

        $order_model = new Order();
        $data = [
            'commission_state' => $state,
        ];
        if($state == COMMISSION_STATE_INVALID) {
            // 失效的，清除订单上的佣金
            $data['commission'] = 0;
            $data['commission_sale'] = 0;
            # 如果佣金状态是 已结算COMMISSION_STATE_SUCCESS
            $where = [
                'order_id' => $order['order_id'],
                'state' => COMMISSION_STATE_SUCCESS,
            ];
            # 查询代理人的余额足够不足够扣除佣金
            $list = Db::name('commission')->field('id,amount,inviter_id,order_sn,remark')->where($where)->select();

            $predeposit_model = new Predeposit();
            // 已结算余额退款
            foreach ($list as $item) {
                $member = (new Member())->getMemberInfoByID($item['inviter_id']);
                if($member['available_predeposit'] < $item['amount']) throw new Exception('余额不足，无法进行处理，请联系客服人员');

                // 余额变更
                $commission_data = array();
                $commission_data['member_id'] = $item['inviter_id'];
                $commission_data['member_name'] = $member['member_name'];
                $commission_data['amount'] = $item['amount'];
                $commission_data['order_sn'] = $item['order_sn'];
                $commission_data['admin_name'] = '系统';
                $commission_data['lg_desc'] = $item['remark'];
                $predeposit_model->changePd('refund_commission_cancel', $commission_data);
            }
        }

        # 修改 没有进行结算佣金的订单
        $order_model->editOrder($data, array(
            'order_id' => $order['order_id'],
            'commission_state' => ['lt', COMMISSION_STATE_SUCCESS]
        ));

    }

    /**
     * 未到账总余额
     */
    public function get_not_arrival_total($member_id){
        $where = array();
        $where['inviter_id'] = $member_id;
        $where['state'] = ['in', [COMMISSION_STATE_CALC, COMMISSION_STATE_ACTIVE]];
        $total = Db::name('commission')->where($where)->sum('amount');
        return $total;
    }

    /**
     * 佣金总计
     * @param $condition
     * @return float|int
     */
    public function totalAmount($condition) {
        $total = Db::name('commission')->where($condition)->sum('amount');
        return $total;
    }
}
